package com.qf.SpringSecurity;

import com.qf.util.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @ClassName: JwtAuthenticationTokenFilter
 * @Author: WangHao
 * @Date: 2025/5/8 13:41
 * @Description:
 * @Version: 1.0
 */

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = jwtUtils.getToken(request);

        // 如果jwt不为空，并且认证信息还未放入上下文，则解析jwt
        if (!ObjectUtils.isEmpty(token) && SecurityContextHolder.getContext().getAuthentication() == null) {
            // 验证token 如果token校验失败，则抛出异常
            jwtUtils.validateToken(token);
            // 刷新令牌时间
            jwtUtils.refreshToken(token);

            Claims claims = jwtUtils.parseJWT(token);
            List<String> authorities = claims.get("perms", List.class);
            // 字符串使用指定的符号拼接成一个完整的字符串
            String authoritiesString = String.join(",", authorities);
            UsernamePasswordAuthenticationToken authenticationToken =
                    new UsernamePasswordAuthenticationToken(claims.get("username"),
                            null,
                            AuthorityUtils.commaSeparatedStringToAuthorityList(authoritiesString));
            authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            // 放入上下文
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }
        filterChain.doFilter(request, response);
    }
}
